/**
 * 
 */
package com.witframework.web.servlet;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Hashtable;

import com.witframework.WitException;

/**
 * @author wuxinyang
 * Jun 15, 2009 11:52:26 AM
 * 
 */
public class Jsps {
	public final static String BASE = "WEB-INF/classes/";
	static Jsps jsps;
	static Hashtable<String, String> jspfile=new Hashtable<String, String>();
	static{
		jsps=new Jsps();
	}
	public static Jsps getInstance(){
		return jsps;
	}
	public synchronized String createJspPage(String url) throws WitException{
		if(jspfile.get(url)==null){
			OutputStream out=null;
			InputStream in=null;
			try {				
				in =this.getClass().getResourceAsStream("/"+url);
				URL resourceURL=this.getClass().getResource("/"+url);
				String path=resourceURL.getFile();
			    path=path.substring(6,path.indexOf("WEB-INF"));
			    String target=path+BASE+url;
			    java.io.File f=new java.io.File(target.substring(0,target.lastIndexOf("/")));
			    f.mkdirs();
			    out = new java.io.FileOutputStream(target);
				if(resourceURL==null){
					System.out.println("resource not found (" + url + ")");
				}else{				
					if (in == null) {
						throw new WitException("resource not found (" + url + ")");
					}				
					byte[] buffer = new byte[10240];
					int len = -1;
					while ((len = in.read(buffer)) != -1) {					
						out.write(buffer, 0, len);						
					}
					out.flush();
				}
				jspfile.put(url,"");
			} catch (Exception e) {			
				throw new WitException(e);
			}finally {
				try { in.close(); out.close(); } catch (Exception e) { }
			}
		}
		return BASE+url;
	}
}
